package com.wanyangproject.net.util;

import android.app.Activity;

import com.wanyangproject.activity.LoginActivity;

import java.util.Stack;

public class ActivityManager {

	private static Stack<Activity> mActivityStack;
	private static ActivityManager mActivitiesManager;

	private ActivityManager() {
	}

	public static ActivityManager getInstance() {
		if (null == mActivitiesManager) {
			mActivitiesManager = new ActivityManager();
			if (null == mActivityStack) {
				mActivityStack = new Stack<>();
			}
		}
		return mActivitiesManager;
	}

	public void out(Activity activity) {
		if (null != activity) {
			mActivityStack.remove(activity);
			activity = null;
		}
	}

	public void in(Activity activity) {
		if(activity instanceof LoginActivity) {
			outAll();
		}
		mActivityStack.add(activity);
	}

	public void outAll() {
		while (!mActivityStack.isEmpty()) {
			Activity activity = getCurrentActivity();
			if (null == activity) {
				break;
			}
			activity.finish();
			out(activity);
		}
	}

	private Activity getCurrentActivity() {
		Activity activity = null;
		try {
			activity = mActivityStack.lastElement();
		} catch (Exception e) {
			return null;
		}
		return activity;
	}
}
